import React, { FC, useState, useEffect } from 'react'
import { Button, message, Divider } from 'antd'

import ProductionVoucher from '~/components/production-voucher'
import TopHeader, { ListTitle } from '~/components/top-header'
import { useNavigate, useLocation } from 'react-router-dom'
import { queryCastItems, handleReceive, handleGiveBack } from '~/api/accept-property-api'
import { getUserInfo } from '~/mock/user/userinfo'
import SuccessModal from '~/components/submit-successfully'
import { formatTime } from '~/utils/utils'
import UploadCom from '~/components/my-upload'

import WaitingList from './container/waiting-list'
import MovedList from './container/moved-list'
import { FooterAction } from './styled'

const docs = new Map()

const isSpecializedStaff = JSON.parse(localStorage.getItem('u')!).roles.includes('KEEPER')

const PropertyInvolved: FC = () => {
  const navigate = useNavigate()
  const { state }: any = useLocation()
  const [certificateVisible, setCertificateVisible] = useState(false)
  const [successVisible, setSuccessVisible] = useState(false)
  const [caseItmes, setCaseItems] = useState([])
  const [selectItmes, setSelectItems] = useState([])
  const {
    batchNo,
    caseName,
    createTime,
    caseNo,
    caseCompanyName,
    caseDepartmentName,
    caseState,
    createCompanyName,
    createDepartmentName
  } = state

  const isWait = caseState === 1

  const onClickCertificate = async (preview?: boolean) => {
    const userInfo = getUserInfo()
    const { data } = await handleReceive({
      ...userInfo,
      batchNo,
      caseName,
      docs: [...docs.values()],
      caseNo,
      preview: !!preview
    })
    window.open(data.url)
    if (preview) return
    setSuccessVisible(true)
  }

  console.log('selectItmes', selectItmes)

  const onClickGiveBackItems = async () => {
    if (!selectItmes.length) return message.error('请至少选择一个物品')
    const userInfo = getUserInfo()
    await handleGiveBack({
      ...userInfo,
      batchNo,
      serialNos: selectItmes
    })
    const code = await handleGetCaseItems()
    console.log('code!!!', code)
    code === '000202' ? navigate(-1) : message.success('退回物品成功')
  }

  const handleGetCaseItems = async () => {
    const userInfo = getUserInfo()
    const { data = [], code } = await queryCastItems({
      batchNo,
      statusList: isWait ? ['WAIT'] : ['SUCCESS'],
      ...userInfo
    })
    setCaseItems(data)
    return code
  }

  useEffect(() => {
    handleGetCaseItems()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const headData = [
    {
      childen: [
        {
          label: '案件编号:',
          value: caseNo
        },
        { label: '案件名称:', value: caseName }
      ]
    },
    {
      childen: isWait
        ? [
            { label: '办案单位:', value: caseCompanyName || createCompanyName },
            { label: '办案部门:', value: caseDepartmentName || createDepartmentName }
          ]
        : [
            { label: '移交时间:', value: formatTime(createTime) },
            { label: '批次号:', value: batchNo }
          ]
    }
  ]

  return (
    <div>
      <TopHeader headData={headData} />
      <ListTitle />
      <main style={{ marginTop: 21 }}>
        {/* <Form layout="inline" form={form} style={{ marginBottom: 16 }}>
          <Form.Item name="1" label="案件编号：">
            <Input placeholder="请输入案件编号搜索" />
          </Form.Item>
          <Form.Item name="2" label="案件名称：">
            <Input placeholder="请输入案件名称搜索" />
          </Form.Item>
          <Form.Item>
            <Button onClick={() => resetFields()} type="link" style={{ padding: 0 }}>
              清空选项
            </Button>
          </Form.Item>
        </Form> */}
        {isWait ? (
          <WaitingList selectItmes={selectItmes} setSelectItems={setSelectItems} caseItmes={caseItmes} />
        ) : (
          <MovedList caseItmes={caseItmes} />
        )}

        {isWait && (
          <>
            <h3>上传法律文书</h3>
            <Divider />
            <UploadCom
              frontend="frontendedoc"
              onSuccess={({ storeId, name, files }: any) => {
                console.log('files', files)
                docs.set(files.name, { storeId, name })
              }}
              onRemove={(file: any) => {
                docs.delete(file.name)
                console.log('onRemove', file)
              }}
            />
          </>
        )}
        <FooterAction>
          <div>
            {isWait ? (
              <div>
                <Button onClick={onClickGiveBackItems}>退回物品</Button>
                <Button
                  onClick={() => {
                    navigate(-1)
                  }}
                  style={{ marginLeft: 8 }}
                >
                  返回
                </Button>

                <Button onClick={() => onClickCertificate(true)} style={{ marginLeft: 8 }}>
                  预览{isSpecializedStaff ? '交接' : '集中保管'}凭证
                </Button>
                <Button onClick={() => onClickCertificate()} style={{ marginLeft: 8 }} type="primary">
                  制作{isSpecializedStaff ? '交接' : '集中保管'}凭证
                </Button>
              </div>
            ) : (
              <Button
                onClick={() => {
                  navigate(-1)
                }}
                style={{ marginLeft: 8 }}
              >
                返回
              </Button>
            )}
          </div>
        </FooterAction>
        <ProductionVoucher
          onOk={() => {
            setCertificateVisible(false)
          }}
          onCancel={() => {
            setCertificateVisible(false)
          }}
          visible={certificateVisible}
        />
      </main>
      <SuccessModal visible={successVisible} />
    </div>
  )
}

export default PropertyInvolved
